package com.xbongbong.rule.symbol;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.rule.symbol.base.AbstractSymbol;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author zheng.li
 **/
@Slf4j
public class RangeSymbol extends AbstractSymbol {

    @Override
    public boolean operation() {
        if (StringUtil.isEmpty(value.toString()) || !Objects.equals(conditionValueList.size(), BasicConstant.TWO)) {
            return false;
        }
        if (attr.contains(FieldTypeEnum.SUB_FORM.getEsalias()) && attr.contains(StringConstant.POINT)) {
            //子表单
            JSONArray arrayValue = factJson.getJSONArray(attr);
            if (CollectionsUtil.isNotEmpty(arrayValue)) {
                return arrayValue.stream().anyMatch(v -> compare(v.toString()));
            }
        } else {
            return compare(value.toString());
        }
        return false;
    }

    private boolean compare(String realValue) {
        BigDecimal valueDecimal;
        BigDecimal startDecimal;
        BigDecimal endDecimal;
        try {
            valueDecimal = new BigDecimal(realValue);
            startDecimal = new BigDecimal(conditionValueList.get(0).toString());
            endDecimal = new BigDecimal(conditionValueList.get(1).toString());
        } catch (Exception e) {
            log.error("转换类型错误,value=" + value + "   conditionValueStr=" + conditionValueList.toString(), e);
            return false;
        }
        return valueDecimal.compareTo(startDecimal) > -1 && valueDecimal.compareTo(endDecimal) < 0;
    }
}
